package com.micro.quartz;

import com.micro.model.KnowLib;
import com.micro.model.Product;
import com.micro.service.KnowLibService;
import com.micro.service.ProductService;
import com.micro.util.DynamicDataSourceHolder;
import net.sf.json.JSONObject;
import okhttp3.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ProductJob {
    private static OkHttpClient client = new OkHttpClient();
    private ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:conf/spring.xml"
            ,"classpath:conf/spring-mybatis.xml"});
    String webhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=7df370a8957685b6150603d8c524c8c6981821c19ba56b9565945556d07c3c80";

    public void pushVersionPlan() {
        ProductService productService = (ProductService) context.getBean("productServiceImpl");
        KnowLibService knowLibService = (KnowLibService) context.getBean("knowLibServiceImpl");
        List<KnowLib> knowLibList = knowLibService.queryKnowLibList();
        if (null != knowLibList && knowLibList.size() > 0) {
            for (int j = 0; j < knowLibList.size(); j++) {
                KnowLib knowLib = knowLibList.get(j);
                if (null != knowLib && "TestingDepartment".equals(knowLib.getKnowCode())) {
                    webhookUrl = knowLib.getKnowDingding();
                    break;
                }
            }
        }
        System.out.println("webhookUrl:" + webhookUrl);
        // 测试写死hook地址
        // webhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=7df370a8957685b6150603d8c524c8c6981821c19ba56b9565945556d07c3c80";
        DynamicDataSourceHolder.setDataSource("dataSource2");
        List<Product> productList = productService.queryProductPlanByDay(null);
        String strNow = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
        String title = strNow + " 版本计划：请关注哇！";
        String message = "### " + strNow + " 版本计划：请关注！" + "\n ";
        for (int i = 0; i < productList.size(); i++) {
            Product productItem = productList.get(i);
            message += "> " + (i+1) + ". " + productItem.getPatchCode() + "; **" + productItem.getTe() + "**" + "\n\n ";
        }
        if (null != productList && productList.size() > 0) {
            try {
                JSONObject text = new JSONObject();
                text.put("title", title);
                text.put("text", message);

                JSONObject atWho = new JSONObject();
                atWho.put("isAtAll", "true");

                JSONObject json = new JSONObject();
                json.put("msgtype", "markdown");
                json.put("markdown", text);
                json.put("at", atWho);
                String jsonString = json.toString();

                String type = "application/json; charset=utf-8";
                RequestBody body = RequestBody.create(MediaType.parse(type), jsonString);
                if (null != webhookUrl && !"".equals(webhookUrl)) {
                    Request.Builder builder = new Request.Builder().url(webhookUrl);
                    builder.addHeader("Content-Type", type).post(body);

                    Request request = builder.build();
                    Response response = client.newCall(request).execute();
                    String resStr = response.body().string();
                    System.out.println(String.format("send ding message:%s", resStr));
                }
            }  catch (Exception e) {
                e.printStackTrace();
                //logger.error("发送钉钉消息错误！ ", e);
            }
        }
    }

    public static void main(String[] args) {
        ProductJob productJob = new ProductJob();
        productJob.pushVersionPlan();
    }
}
